<template>
  <!-- 头部组件 -->
  <view class="custom-header">
    <!-- 头像 -->
    <view class="custom-header-avatar" @click="emits('open')">
      <acatar :size="74" :title="props?.title" :img="img" />
    </view>
    <!-- 右侧内容 -->
    <view class="custom-header-extra">
      <!-- <img src="../../static/header/search.svg" class="custom-header-use-svg" /> -->
      <img src="../../static/header/scan.svg" class="custom-header-use-svg" @click="scanQRCode" />
    </view>
  </view>
  <dropDownModal :show="props.show" :userInfo="orgCtl.user" @close="emits('close')" :list="INFOLIST" :className="'leftTop'" @menuClick="menuClick" />
  <scanModal :show="isScan" :targetId="targetId" @closeScanModal="closeScanModal" @confirmScanModal="confirmScanModal"></scanModal>

  <tm-modal
    v-model:show="shareScanModalShow"
    :overlayClick="false"
    title="请输入密码"
    :height="350"
    @confirm.stop="loadForm"
    @cancel.stop="shareScanModalShow = false"
    @close.stop=""
  >
    <tm-input v-model.trim="queryObj.password" :maxlength="11" placeholder="请输入密码" />
  </tm-modal>
</template>

<script lang="ts" setup>
import acatar from './acatar.vue'
import dropDownModal from '@/components/customModal/dropDownModal.vue'
import scanModal from '@/components/scanModal/scanModal.vue'
import { INFOLIST } from '@/common/constant/index'
import msAppletApi from '@/utils/ms_applet_api'
import orgCtl from '@/ts/controller'
import { ref } from 'vue'
// #ifdef H5
import zzd from 'gdt-jsapi'
// #endif

type Props = {
  title?: string
  show?: boolean
}
const props = defineProps<Props>()
const emits = defineEmits(['close', 'open', 'menuClick', 'closeScanModal', 'confirmScanModal'])
const isScan = ref<boolean>(false)
const shareScanModalShow = ref<boolean>(false)
const targetId = ref<string>('')
const img = ref(orgCtl.user.share.avatar?.thumbnail)
//请求相关初始参数
const loadOptions: any = {
  filter: ['id', '='],
  requireTotalCount: true,
  searchOperation: 'contains',
  searchValue: null,
  skip: 0,
  take: 20,
  userData: [],
  sort: [
    {
      selector: 'id',
      desc: false
    }
  ],
  group: null
}
/** 菜单点击事件 */
const menuClick = (value: string) => {
  if (value === 'exitLogin') {
    // #ifdef H5 || MP-ALIPAY
    const token = uni.getStorageSync('accessToken')
    uni.request({
      url: 'http://zydd.orginone.org.cn/ZZDLogin.unbind',
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        accessToken: token
      },
      success: _res => {},
      fail: _err => {}
    })
    // #endif
    uni.reLaunch({
      url: '/pages/auth/login?clear=1'
    })
  } else if (value === 'userInfo') {
    uni.navigateTo({
      url: '/pages/auth/userInfo'
    })
    emits('close')
  }
}

let queryObj: Record<string, string> = {}
const scanQRCode = async () => {
  // #ifndef H5
  msAppletApi.scanCode({
    success: async (res: string) => {
      queryObj = {}
      // 解析二维码参数
      const queryString = res.split('?')[1]
      if (!queryString) return uni.showToast({ title: '二维码错误', icon: 'error' })
      queryString.split('&').forEach(pair => {
        const [key, value] = pair.split('=')
        queryObj[key] = decodeURIComponent(value || '') // 处理特殊字符
      })

      await loadForm()
    },
    fail(res: string) {
      uni.hideLoading()
      console.log(res) // 扫描失败的错误信息
    }
  })
  // #endif

  // #ifdef H5
  zzd
    .scan({
      type: 'qrCode'
    })
    .then(res => {
      const result = res.text.split('/')
      const _targetId = result[result.length - 1]
      targetId.value = _targetId
      isScan.value = true
    })
    .catch(_err => {
      uni.showToast({
        title: '扫码错误，请稍后重试...',
        icon: 'none',
        duration: 3000
      })
    })
  // #endif
}
const loadForm = async () => {
  try {
    uni.showLoading({ title: '正在加载' })
    if (!queryObj.key) return uni.showToast({ title: '扫码参数错误', icon: 'none' })
    const { code, data, msg } = await orgCtl.loadFormByQRCode(queryObj.key, queryObj.password)
    if (msg === '访问密码不正确，请核对后再次操作！') {
      shareScanModalShow.value = false
      shareScanModalShow.value = true
      return
    }
    if (code !== 200) return uni.showToast({ title: msg || '加载失败', icon: 'none' })
    shareScanModalShow.value = false
    if (JSON.parse(data.remark).type !== '表单') return uni.showToast({ title: '请扫描表单分享二维码', icon: 'error' })

    const attr = data.resource.find((item: any) => item.remark === 'attr') || {}
    const { data: fields } = await orgCtl.loadFormByQRCode(queryObj.key, queryObj.password, attr.id)
    const thing = data.resource.find((item: any) => item.remark === 'thing') || {}
    const { data: localFormData } = await orgCtl.loadFormByQRCode(queryObj.key, queryObj.password, thing.id)

    if (!attr.fields && !localFormData.length) return uni.showToast({ title: '表单无数据', icon: 'error' })
    uni.navigateTo({
      url: '/pages/open/formInfo',
      success: function (res) {
        res.eventChannel.emit('formInfo', {
          localFormData: localFormData[0],
          fields
        })
      }
    })
  } finally {
    uni.hideLoading()
  }
}

// 取消弹窗
const closeScanModal = () => {
  isScan.value = false
}
// 确认弹窗
const confirmScanModal = () => {
  isScan.value = false
}
</script>

<style lang="scss">
.custom-header {
  width: 100vw;
  height: 96rpx;
  padding: 16rpx 24rpx 16rpx 32rpx;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  .custom-header-extra {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .custom-header-use-svg {
      width: 50rpx;
      height: 50rpx;
      margin-right: 12rpx;
    }
    .custom-header-use-svg-last {
      width: 50rpx;
      height: 50rpx;
    }
  }
}
</style>
